package com.lzy.cloud.search.client.service.impl;

import com.lzy.cloud.search.client.entity.EsIndex;
import com.lzy.cloud.search.client.service.BulkDocumentService;
import com.lzy.cloud.search.client.util.EsClient;
import org.elasticsearch.action.bulk.BulkRequestBuilder;
import org.elasticsearch.action.bulk.BulkResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder;

/**
 * 批量插入文档
 */
@Service
public class BulkDocumentServiceImpl implements BulkDocumentService {

    @Autowired
    private EsClient client;

    public void prepareBulk(List<EsIndex> indexList) {


        BulkRequestBuilder bulkRequest = client.getConnection().prepareBulk();

        for (EsIndex esIndex : indexList) {
            bulkRequest.add(client.getConnection().prepareIndex(esIndex.getName(), esIndex.getType(), esIndex.getId())
                    .setSource(esIndex.getDocumentMap())
            );
        }

//        bulkRequest.add(client.getConnection().prepareIndex("twitter", "tweet", "11")
//                .setSource(jsonBuilder()
//                        .startObject()
//                        .field("user", "kimchy")
//                        .field("postDate", new Date())
//                        .field("message", "another post")
//                        .endObject()
//                )
//        );

        BulkResponse bulkResponse = bulkRequest.get();
        if (bulkResponse.hasFailures()) {
            // process failures by iterating through each bulk response item
            //处理失败


            System.out.println("失败：" + bulkResponse.toString());
        }
    }
}
